/* 

  FITS related utility


  Copyright © 2011 F.Hroch (hroch@physics.muni.cz)

  This file is part of Munipack.

  Munipack is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.
  
  Munipack is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
  
  You should have received a copy of the GNU General Public License
  along with Munipack.  If not, see <http://www.gnu.org/licenses/>.


*/

#include "fitsut.h"
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <string.h>
#include <fitsio.h>

using namespace std;


int header(const string& filename, const vector<string>& keywords, int keylist)
{
  fitsfile *f;
  int status = 0;

  status = 0;
  if( fits_open_file(&f, filename.c_str(), READONLY, &status) )
    fits_report_error(stderr, status);

  if( ! keywords.empty() ) {
    /* print selected keys */

    int ninc = keywords.size();
    char **inclist = (char **) malloc(sizeof(char *)*ninc);

    for(int i = 0; i < ninc; i++)
      inclist[i] = strdup(keywords[i].c_str());
      
    char record[FLEN_CARD];
    fits_read_record(f,0,record,&status); // useless, but resets init position

    if( keylist == ID_FULL ) {

      while( fits_find_nextkey(f,inclist,ninc,NULL,0,record,&status) == 0 )
	cout << record << endl;

    }
    else if( keylist == ID_SHORT ) {
     
      int keylen;
      char keyname[FLEN_KEYWORD],value[FLEN_VALUE],comment[FLEN_COMMENT];

      while( fits_find_nextkey(f,inclist,ninc,NULL,0,record,&status) == 0 ) {
	fits_get_keyname(record,keyname,&keylen,&status);
	fits_parse_value(record,value,comment,&status);
	cout << keyname << " = " << value << endl;
      }
    }

    for(int i = 0; i < ninc; i++)
      free(inclist[i]);
    free(inclist);

    if( status == KEY_NO_EXIST )
      status = 0;

  }
  else {

    /* print full header */
    int nhead;
    char record[FLEN_CARD];
    
    fits_get_hdrspace(f,&nhead,NULL,&status);
    for(int i = 0; status == 0 && i < nhead; i++) {
      if( fits_read_record(f,i+1,record,&status) == 0 )
	cout << record << endl;
    }
    
  }

  fits_close_file(f, &status);

  if( status != 0 )
    fits_report_error(stderr, status);

  return status;
}
